package com.df.library.net;

import com.df.library.net.condition.IProtocolPredicate;
import com.df.library.net.handler.ProtocolSelectHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.List;

/**
 * 多协议服务,同一个端口支持多个协议，具体协议需要动态切换
 */
public class MultiProtocolServer extends CommonServer{

    public MultiProtocolServer(String name, int port, List<Class<? extends IProtocolPredicate>> conditions){
        if(conditions==null || conditions.isEmpty()){
            throw new RuntimeException("多协议服务器没有设置协议判断");
        }
        setName(name);
        addListenPort(port);

        setChannelInitializer(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                //每次请求都要动态判断是什么类型的请求，因此ProtoclSelectHandler每次有连接都要new一个实例
                ProtocolSelectHandler protocolSelectHandler = new ProtocolSelectHandler();
                protocolSelectHandler.addConditions(conditions);
//                socketChannel.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                socketChannel.pipeline().addLast(protocolSelectHandler);
            }
        });
    }
}
